#include "sharedMemory.h"

static int blocs[MEM_SIZE];

static void* mapped_file;

static int mem_size;

static size_t size_of(char* filename);

void allocMemory(){
    int file_desc;
    
    int i;
    for(i = 0; i<MEM_SIZE; i++){
        blocs[i] = -1;
    }
    
    file_desc = open(MEM_FILE, O_RDWR | O_CREAT | O_TRUNC, 0666);
    if(file_desc == -1){
        perror("Shared memory : cannot open file");
        exit(EXIT_FAILURE);
    }
    
    for (i = 0; i < MEM_SIZE; ++i) {
        if (write(file_desc, "0", 1) == -1) {
            perror("initSharedMemory -> write");
            exit(-1);
        }
    }

    mapped_file = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, file_desc, 0);
    if(mapped_file == (void*)-1){
        perror("Alloc memory : cannot map file");
        exit(EXIT_FAILURE);
    }
    
    mem_size = MEM_SIZE;
    close(file_desc);
    
}

void freeBloc(unsigned int bloc_num){
    if(bloc_num < MEM_SIZE){
        blocs[bloc_num] = -1;
        memset(mapped_file + (bloc_num*BLOC_LENGHT), '0', BLOC_LENGHT);
    }
}

void setBloc(unsigned int bloc_num, void* datas){
    if (bloc_num<MEM_SIZE) {
        memcpy(mapped_file + (bloc_num*BLOC_LENGHT), datas, BLOC_LENGHT);
    }
}

char* getBloc(unsigned int bloc_num){
    char* pt = NULL;
    if (bloc_num >= 0 && bloc_num < MEM_SIZE) pt = mapped_file + (bloc_num * BLOC_LENGHT);
    return pt;
}

void freeMemory(){
    if (munmap(NULL, mem_size) == -1) {
            perror("free memory failed");
            exit(EXIT_FAILURE);
    }
}

int getNewBloc(){
    int i;
    for (i = 0; i < MEM_SIZE; i++) {
        if (blocs[i] == -1) {
            blocs[i] = 0;
            return i;
        }
    }
    return -1;
}

